//
//  XJGoodsViewController.m
//  XinJiangMall
//
//  Created by Tzyang on 2018/4/2.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJGoodsViewController.h"
#import "XJHttpTool.h"
// Model
#import "XJLeftTableModel.h"
#import "XJRightCollectionModel.h"
//View
#import "XJLeftTableViewCell.h"
#import "XJRightCollectionViewCell.h"
#import "XJRightCollectionSectionHeaderView.h"

// Controller
#import "XJCtySecondViewController.h" // 点击item跳转二级页面



static float kLeftTv_W = 80.f; // tableView宽度
static float kClvMargin = 3.f; // clv 间距
static NSString *const XJLeftTableViewCellId = @"XJLeftTableViewCellId";
static NSString *const XJRightCollectionViewCellId = @"XJRightCollectionViewCellId";
static NSString *const XJRightClvSectionHeaderId = @"XJRightClvSectionHeaderId";


@interface XJGoodsViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    NSInteger _selectIndex; // 标记点击的小标
    BOOL _isScrollDown; // 标记clv滚动的方向。
}

@property(nonatomic, strong) UITableView *leftTableView;
@property(nonatomic, strong) UICollectionView *rightClv;
/**tableVeiw 的数据源数组*/
@property(nonatomic, strong) NSMutableArray *tvArr;
/**collectionView 的数据源数组*/
@property(nonatomic, strong) NSMutableArray *clvArr;
@end

@implementation XJGoodsViewController
#pragma mark - lazy
- (NSMutableArray *)tvArr {
    if (!_tvArr) {
        _tvArr = [NSMutableArray array];
    }
    return _tvArr;
}
- (NSMutableArray *)clvArr {
    if (!_clvArr) {
        _clvArr = [NSMutableArray array];
    }
    return _clvArr;
}

- (UITableView *)leftTableView {
    if (!_leftTableView) {
        _leftTableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone; //取消分割线
        _leftTableView.tableFooterView = [UIView new];
        
        [_leftTableView registerClass:[XJLeftTableViewCell class] forCellReuseIdentifier:XJLeftTableViewCellId];
    }
    return _leftTableView;
}

- (UICollectionView *)rightClv {
    if (!_rightClv) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.minimumLineSpacing = 2;
        layout.minimumInteritemSpacing = 2;
        layout.headerReferenceSize = CGSizeMake(KWidth, 30); // sectionHeader的高度
        
        _rightClv = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _rightClv.backgroundColor = [UIColor whiteColor];
        
        _rightClv.delegate = self;
        _rightClv.dataSource = self;
        
        // 注册item sectionHeader
        [_rightClv registerClass:[XJRightCollectionViewCell class] forCellWithReuseIdentifier:XJRightCollectionViewCellId];
        [_rightClv registerClass:[XJRightCollectionSectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:XJRightClvSectionHeaderId];
    }
    return _rightClv;
}
#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle= @"分类";
    self.navButtonRight.hidden = NO;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupUI];
    
    [self requestCtyData];
}
#pragma mark - UI
- (void)setupUI {
    // 要适配iphoneX 。nav+tabbar
    self.leftTableView.frame = CGRectMake(0, 0, kLeftTv_W, KHeight-44);
    [self.view addSubview:self.leftTableView];
    
    CGFloat clv_x = kLeftTv_W + kClvMargin;
    CGFloat clv_w = KWidth - kLeftTv_W - kClvMargin;
    self.rightClv.frame = CGRectMake(clv_x, 0, clv_w, KHeight - 44);
    [self.view addSubview:self.rightClv];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tvArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XJLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:XJLeftTableViewCellId forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.tvArr[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 标记当前点击的cell的小标row
    _selectIndex = indexPath.row;

    
    //作用:实现右边clv圆点样色的切换
    //1.现将所有的的状态都清空。
    for (XJLeftTableModel *model in self.tvArr) {
        model.isChecked = NO;
    }
    //2.将当前的选中的 model 标记为选中状态。
    XJLeftTableModel *model = self.tvArr[indexPath.row];
    model.isChecked = YES;
    //3.刷新右边的clv:注意刷新的时机. 在这里刷新右边的clv就不滚动了(1.滚动,2.刷新 两件事有冲突。刷新应该在滚动之后做。)。
//    [self.rightClv reloadData];
    
    
    // 编辑tableView 滚动 clv
    [self rb_scrollToTopOfSection:_selectIndex animated:YES];
    
    
    [self.rightClv reloadData]; //1.先滚动 2.在刷新
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.clvArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *tmpArr = self.clvArr[section];
    return tmpArr.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        XJRightCollectionSectionHeaderView *sectionHeaderV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:XJRightClvSectionHeaderId forIndexPath:indexPath];
        
        // 给标题赋值
        sectionHeaderV.model = self.tvArr[indexPath.section];
        
        return sectionHeaderV;
    }else {
        return nil;
    }
}
// 返回clv的item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XJRightCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:XJRightCollectionViewCellId forIndexPath:indexPath];
    
    XJRightCollectionModel *model = self.clvArr[indexPath.section][indexPath.row];
    
    cell.clvModel = model;
    return  cell;
}

#pragma mark - UICollectionViewDelegate
/**点击item*/
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
   XJRightCollectionModel *didModel  =  self.clvArr[indexPath.section][indexPath.row];
    XJLog(@"%ld--%ld-%@-%@",indexPath.section,indexPath.row,didModel.name,didModel);
    
    
    XJCtySecondViewController *ctySecondVC = [[XJCtySecondViewController alloc] init];
    
    ctySecondVC.category_id = didModel.goodsId;
    ctySecondVC.navigationItem.title = didModel.name;
    
    [self.navigationController pushViewController:ctySecondVC animated:YES];
}


#pragma mark - UICollectionViewDelegateFlowLayout 布局item
// 设置item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 想要每行显示3个item
    CGFloat item_w = (KWidth - kLeftTv_W - kClvMargin*4) / 3;
    return CGSizeMake(item_w, item_w +ADAPTHeight(15));
}

#pragma mark - 联动
#pragma mark - 解决点击 TableView 后 CollectionView 的 Header 遮挡问题
// 第一个目标:点击tableView cell 滚动 collectionView
- (void)rb_scrollToTopOfSection:(NSInteger)section animated:(BOOL)animated
{
    
    CGRect headerRect = [self rb_frameForHeaderForSection:section];
    CGPoint topOfHeader = CGPointMake(0, headerRect.origin.y - self.rightClv.contentInset.top);
    [self.rightClv setContentOffset:topOfHeader animated:animated];
    
}

- (CGRect)rb_frameForHeaderForSection:(NSInteger)section
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:section];
    UICollectionViewLayoutAttributes *attributes = [self.rightClv.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
    
    // 拿到对应的sectionHeaderView 修改黄点的状态。
    
    return attributes.frame;
}

// 第二个目标:滚动 collectionView 对应的tableView也要滚动。
//- didEndDisplayingSupplementaryView
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    if (_isScrollDown && (collectionView.dragging || collectionView.decelerating)) {
        
        [self rb_selectRowAtIndexPath:indexPath.section + 1];
    }
}

// 当拖动CollectionView的时候，处理TableView
- (void)rb_selectRowAtIndexPath:(NSInteger)index
{
    [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}

#pragma mark - UIScrollView Delegate 判断clv滚动方向
// 标记一下CollectionView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static float lastOffsetY = 0;
    
    if (self.rightClv == scrollView)
    {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

#pragma mark - 获取数据
- (void)requestCtyData {
    [XJHttpTool requestCategoryDataSuccessHandler:^(id responseObjc) {
       
       NSArray *listArr = responseObjc[@"data"][@"list"];
        
        // tableView 模型
        for (NSDictionary *dic1 in listArr) {
           XJLeftTableModel *leftM = [XJLeftTableModel mj_objectWithKeyValues:dic1[@"root_categroy"]];
            [self.tvArr addObject:leftM];
        }
        
        // collectionView 模型
        for (NSDictionary *dic2 in listArr) {
            NSArray *ctyListArr = dic2[@"category_list"];
            NSMutableArray *newArr = [NSMutableArray array];
            
            for (NSDictionary *dic3 in ctyListArr) {
                XJRightCollectionModel *clvM = [XJRightCollectionModel mj_objectWithKeyValues:dic3];
                [newArr addObject:clvM];
            }
            [self.clvArr addObject:newArr];
        }
        
//        NSLog(@"%ld-%@,",(long)self.tvArr.count,self.tvArr);
//        NSLog(@"%ld-%@,",(long)self.clvArr.count,self.tvArr);
        // 回到主线刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.leftTableView reloadData];
            [self.rightClv reloadData];
        });
    } failureHandler:^(NSError *error) {
        XJLog(@"获取分类数据失败：%@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
